import time
import pyautogui
import cv2
from paddleocr import PaddleOCR
import smtplib
from email.mime.text import MIMEText
# 初始化 PaddleOCR，启用 GPU
ocr = PaddleOCR(use_angle_cls=True, lang='ch', use_gpu=True)

# 定义截图文件路径
name=['top_left','top_right','bottom_left','bottom_right']
qufu=['瑶光','烟雨','天下','沧海']
screenshot_path = "screenshot.png"
email='2391860056@qq.com'
# 定义目标字符串和邮件信息
target_str = "赐福"  # 替换为你需要监测的内容
from PIL import Image

def split_image_into_quarters(image_path, output_dir):
    """
    将一张图片分成4等份，并保存
    :param image_path: 输入图片路径
    :param output_dir: 保存分割图片的目录
    """
    # 打开图片
    img = Image.open(image_path)
    width, height = img.size  # 获取图片宽度和高度

    # 计算分割的区域
    mid_width = width // 2
    mid_height = height // 2

    # 定义四个区域
    regions = {
        "top_left": (0, 0, mid_width, mid_height),
        "top_right": (mid_width, 0, width, mid_height),
        "bottom_left": (0, mid_height, mid_width, height),
        "bottom_right": (mid_width, mid_height, width, height),
    }

    # 裁剪并保存每个区域
    for region_name, box in regions.items():
        cropped_img = img.crop(box)
        cropped_img.save(f"{output_dir}/{region_name}.png")
        print(f"保存区域: {region_name}, 文件路径: {output_dir}/{region_name}.png")

def crop_image(input_image_path, output_image_path):
    # 打开图片
    image = Image.open(input_image_path)

    # 获取图片的宽度和高度
    width, height = image.size

    # 计算裁剪区域的坐标
    left = 0.13 * width  # 左侧起始位置
    top = 0  # 上侧起始位置
    right = 0.13 * width + 0.30 * width  # 右侧宽度
    bottom = height  # 下侧起始位置

    # 裁剪图片
    cropped_image = image.crop((left, top, right, bottom))

    # 保存裁剪后的图片
    cropped_image.save(output_image_path)
    print(f"Cropped image saved at {output_image_path}")
def preprocess_image(image_path):
    """
    图像预处理：灰度化 -> 二值化 -> 降噪
    """
    image = cv2.imread(image_path)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    _, binary = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    return binary

def sendemail(content, price, email):
    mail_user = 'vjmbsd'
    mail_pass = 'HVYZEVNOSEOYSADS'
    sender = 'vjmbsd@163.com'
    receivers = [email]

    message = MIMEText(content, 'plain', 'utf-8')
    message['Subject'] = f'总价：{price}'
    message['From'] = sender
    message['To'] = ';'.join(receivers)

    try:
        smtp = smtplib.SMTP_SSL("smtp.163.com", 465)
        smtp.login(mail_user, mail_pass)
        smtp.sendmail(sender, receivers, message.as_string())
        smtp.quit()
        print('邮件发送成功')
    except smtplib.SMTPException as e:
        print('邮件发送失败', e)
if __name__ == '__main__':
    # 主逻辑循环
    try:
        while True:
            # 截图
            screenshot = pyautogui.screenshot()
            screenshot.save(screenshot_path)
            split_image_into_quarters(screenshot_path, './')
            for i in range(4):
                screenshot_path=name[i]+'.png'
                crop_image(screenshot_path, screenshot_path)
                # 图像预处理
                processed_image = preprocess_image(screenshot_path)
                cv2.imwrite(screenshot_path, processed_image)

                # OCR 识别
                results = ocr.ocr(screenshot_path, cls=True)
                text = "".join([line[1][0] for line in results[0]])
                print(text)
                # 检查目标字符串是否存在
                if target_str in text:
                    print(f"发现目标内容: {target_str}")
                    sendemail(content=f"{qufu[i]}"+text, price="0", email=email)
            # 等待 10 秒
            time.sleep(10)





            
    except KeyboardInterrupt:
        print("程序终止")
